package com.xuyuan.concurrent.test;

public class BuyTicket extends Thread {
    public static int tickets = 20;
    static byte[] bytes = new byte[0];

    public static void main(String[] args) {

        BuyTicket buyTicket = new BuyTicket();
        for (int i = 1; i < 4; i++) {
            Thread t = new Thread(buyTicket, i + "窗口-");
            t.start();
        }

    }

    @Override
    public void run() {

        while (sale()) ;
    }

    public boolean sale() {
        synchronized (bytes) {
            if (tickets > 0) {
                tickets--;
                System.out.println(Thread.currentThread().getName() + "成功出票，剩余票数为" + tickets);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return true;
            } else {
                System.out.println(Thread.currentThread().getName() + "余票不足，停止售票！");
                return false;
            }
        }
    }

}